package com.winsdom.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.winsdom.annotation.OperationLog;
import com.winsdom.dto.CategoryTreeNodes;
import com.winsdom.entity.Category;
import com.winsdom.mapper.CategoryMapper;
import com.winsdom.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;

@RestController
@Api(tags = "测试接口")
@RequestMapping("/test")
public class TestContrller {

    @Autowired
    private CategoryMapper categoryMapper;

    @GetMapping("/test")
    @ApiOperation(value = "展示层级为组织")
    @OperationLog(description = "展示层级为组织")
    public Result test() {
        List<CategoryTreeNodes> categoryTreeNodes = categoryMapper.getCategoryTreeNodes(0L);
        return Result.success(categoryTreeNodes);
    }

    @GetMapping("/test1")
    @ApiOperation(value = "根据当前组织id 展示层级为组织+园区+楼盘")
    @OperationLog(description = "根据当前组织id 展示层级为组织+园区+楼盘")
    public Result test1() {
        // 1. 获取当前节点
        CategoryTreeNodes node = categoryMapper.getNodeById(2L);
        if (node == null) {
            return null;
        }
        // 2. 递归构建子树
        buildSubTree(node);

        return Result.success(node);
    }
    private void buildSubTree(CategoryTreeNodes parentNode) {
        // 查询子节点
        List<CategoryTreeNodes> children = categoryMapper.getChildrenByParentId(parentNode.getId());

        if (!children.isEmpty()) {
            parentNode.setChildren(children);
            // 递归处理每个子节点
            for (CategoryTreeNodes child : children) {
                buildSubTree(child);
            }
        }
    }


    @GetMapping("/test2")
    @ApiOperation(value = "展示层级为组织+园区+楼盘+楼栋+楼层")
    @OperationLog(description = "展示层级为组织+园区+楼盘+楼栋+楼层")
    public Result test2() {
        // 1. 获取根据节点
        CategoryTreeNodes node = categoryMapper.getNodeById(1L);
        if (node == null) {
            return null;
        }
        // 2. 递归构建子树
        buildSubTree2(node);

        return Result.success(node);
    }
    private void buildSubTree2(CategoryTreeNodes parentNode) {
        // 查询子节点
        List<CategoryTreeNodes> children = categoryMapper.getChildrenByParentId2(parentNode.getId());

        if (!children.isEmpty()) {
            parentNode.setChildren(children);
            // 递归处理每个子节点
            for (CategoryTreeNodes child : children) {
                buildSubTree2(child);
            }
        }
    }

    @GetMapping("/test3")
    @ApiOperation(value = "当前账号下已授权的楼盘的资源信息")
    @OperationLog(description = "获取当前账号下已授权的楼盘的资源信息")
    public Result test3() {
        List<Long> authorizedBuildingIds = Arrays.asList(7L, 13L);  //当前账号授权的楼盘id集合
        Long orgId = 1L;  //当前账号的组织ID

        List<CategoryTreeNodes> resourceTree = getAuthorizedResourceTree(orgId, new HashSet<>(authorizedBuildingIds));

        return Result.success(resourceTree);
    }

    public List<CategoryTreeNodes> getAuthorizedResourceTree(Long orgId, Set<Long> authorizedBuildingIds) {
        // 1. 查询所有分类数据
        List<Category> allCategories = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getStatus, 1));

        // 2. 转换为节点映射
        Map<Long, CategoryTreeNodes> idNodeMap = new HashMap<>();
        for (Category category : allCategories) {
            CategoryTreeNodes node = new CategoryTreeNodes();
            BeanUtils.copyProperties(category, node);
            node.setChildren(new ArrayList<>());
            idNodeMap.put(node.getId(), node);
        }

        // 3. 构建父子关系
        for (CategoryTreeNodes node : idNodeMap.values()) {
            CategoryTreeNodes parent = idNodeMap.get(node.getParentId());
            if (parent != null) {
                parent.getChildren().add(node);
            }
        }

        // ✅ 4. 从 orgId 本身作为根节点开始过滤
        CategoryTreeNodes root = idNodeMap.get(orgId);
        if (root == null) {
            return Collections.emptyList(); // orgId 不存在
        }

        CategoryTreeNodes filtered = filterResourceUnderAuthorizedBuildings(root, authorizedBuildingIds);
        if (filtered == null) {
            return Collections.emptyList(); // 无授权资源
        }

        // ✅ 返回带 orgId 的整棵子树
        return Collections.singletonList(filtered);
    }


    private CategoryTreeNodes filterResourceUnderAuthorizedBuildings(CategoryTreeNodes node, Set<Long> authorizedBuildingIds) {
        if (node.getType() == 3 && !authorizedBuildingIds.contains(node.getId())) {   //是否在楼盘ID集合中
            return null;
        }

        List<CategoryTreeNodes> newChildren = new ArrayList<>();
        for (CategoryTreeNodes child : node.getChildren()) {
            CategoryTreeNodes filteredChild = filterResourceUnderAuthorizedBuildings(child, authorizedBuildingIds);
            if (filteredChild != null) {
                newChildren.add(filteredChild);
            }
        }

        node.setChildren(newChildren);

        if (node.getType() == 6 || !newChildren.isEmpty()) {   //type=6  资源
            return node;
        }

        return null;
    }


}
